/**Reservation program
 * 
 * @author locphan
 * @version 1.01
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;


public class Reservation
{
   private static Room room1 = new Room(50);
   private static Room room2 = new Room(200);
   private static GregorianCalendar gcalendar = new GregorianCalendar() ; 

   
   public static void main(String[] args)
   {
      
      
      String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
                "Sep", "Oct", "Nov", "Dec" }; 

      System.out.print("Welcome to the Reservation program ! Today is ");
      System.out.print(months[gcalendar.get(Calendar.MONTH)]);
      System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
      System.out.println(gcalendar.get(Calendar.YEAR));
      System.out.println("Enter the file name that contains existing schedules ");
      
      Scanner input = new Scanner(System.in);
      
      boolean error = true;
      String filename = input.nextLine();

      while(error)
      {
         try
         {
            input = new Scanner(new FileReader(filename));
            error=false;
         } 
         catch (FileNotFoundException e)
         {
            System.out.println("Error! File not found.");
            filename = input.nextLine();         
            error = true;
         }
      }
      System.out.println("Load file successfully.");
      
     
      
      while(input.hasNextLine())
      {
         String line = input.nextLine();
         
         Request request = null;
         try
         {
            request = getRequestFromLine(line);
         } catch (Exception e)
         {
            e.printStackTrace();
         }
         int seats = request.getSeats();
         if(seats<=50 && seats > 0)
         {
            room1.add(request);
         }
         else if(seats <=200 && seats > 50)
         {
            room2.add(request);
         }
         
      }
      input.close();
      
      System.out.println("Commands:"+"1-add, 2-display, 3-cancel, 4-quit"+"\n"+"#:");
      input = new Scanner(System.in);
      boolean flag = true;
      while(flag)
      {
            String nextline = input.nextLine();
         
            if(nextline.compareTo("")==0)
            {
               System.out.println("Please choose a command. 1-add,2-display,3-cancel,4-quit:");
            }
            else
            {
               char response = nextline.charAt(0);
               switch(response)
               {
                  case '1': add(); break;
                  case '2': display(); break;
                  case '3': cancel(); break;
                  case '4': quit();
                  default: System.out.println("Error"); break;
               }
               System.out.println("Commands:"+"1-add, 2-display, 3-cancel, 4-quit"+"\n"+"#:");
               input = new Scanner(System.in); 
               flag=true;
            }
         
         
      }           
   }
   /**
    * Write data from buffer to file and exit
    */
   public static void quit()
   {
      try
      {
         FileWriter first = new FileWriter(new File("output.txt"));
         first.write(room1.toString()+room2.toString());
         first.close();
         
      } catch (IOException e)
      {
         System.out.println("Error. Cannot write to file.");
      }
      System.exit(0);
   }
   /**
    * Cancel a request input by user
    */
   public static void cancel()
   {
      System.out.println("Enter name and month to cancel: (example: Loc Phan;March)");
      try
      {
         Scanner input = new Scanner(System.in);
         String line[] = input.nextLine().split(";");
         int month = getMonthInt(line[1]);
         String name = line[0];
         Request request = new Request(name,null,
                           new GregorianCalendar(gcalendar.get(Calendar.YEAR),month,1),0,0,0);
         System.out.println("Enter room number (1 or 2): ");
         String nextline = input.nextLine();
         if(nextline.compareToIgnoreCase("")==0)
         { System.out.println("Incorrect input.");}
         else
         {
            char room = nextline.charAt(0);
            switch(room)
            {
               case '1': if(room1.cancel(request))
                           { System.out.println("Request Canceled."); }
                        else
                        {
                           System.out.println("Failed to cancel.");
                        }break;
               case '2': if(room2.cancel(request))
                           { System.out.println("Request Canceled."); }
                        else
                           {
                             System.out.println("Failed to cancel.");
                           }break;
                           
                         
            }
         }
         
      }
      catch(Exception e)
      {
         System.out.println("Error.");
      }
      
   }
   
   /**
    * Display selected request from file
    */
   public static void display()
   {
      System.out.println("Enter month to display or 'all' to display all: ");
      Scanner input = new Scanner(System.in);
      String month=input.nextLine();
      if(month.compareToIgnoreCase("all")==0)
      {
         System.out.println("Room 1: "+ room1);
         System.out.println("Room 2: "+ room2);
      }
      else
      {
         try
         {
            int monthint = getMonthInt(month);
            System.out.println("Room 1: "+ room1.printMonthlySchedule(monthint));
            System.out.println("Room 2: "+ room2.printMonthlySchedule(monthint));
   
         }
         catch(IllegalArgumentException e)
         {
            System.out.println("Invalid Month Input.");
         }
      }
   }
   
   /**
    * Add request to buffer
    */
   public static void add()
   {
      System.out.println("Enter a request: (example:Loc Phan;Party;2009;February;28;9;120;20)");
      Scanner input = new Scanner(System.in);
      String line = input.nextLine();
      Request request = null;
      try
      {
         request = getRequestFromLine(line);
         if(request.getStartingTime()>=9 && request.getEndTime()<22)
         {
            int seats = request.getSeats();
            if(seats<=50 && seats > 0)
            {
               room1.add(request);
               System.out.println("Request is added to room #1.");
            }
            else if(seats <=200 && seats > 50)
            {
               room2.add(request);
               System.out.println("Request is added to room #2.");
   
            }   
         }
         else
         {
            System.out.println("Time must be between 9am and 10pm.");
         }
      } 
      catch (IllegalArgumentException e)
      {
         System.out.println("Error occurred. Check your request.");
      }
      catch (ArrayIndexOutOfBoundsException e)
      {
         System.out.println("Invalid Form.");
      }
      catch (Exception e)
      {
         System.out.println("Error.");
      }
      
   }
   
   /**Parse a line to request
    * 
    * @param line input line
    * @return Request
    * @throws ArrayIndexOutOfBoundsException thrown when input is incorrect
    */
   public static Request getRequestFromLine(String line) throws ArrayIndexOutOfBoundsException
   {
      String rawdata[] = line.split(";");
      String name = rawdata[0];
      String eventname = rawdata[1];
      int year = Integer.parseInt(rawdata[2]);
      int month = getMonthInt(rawdata[3]);
      
      int day = Integer.parseInt(rawdata[4]);
      int startingtime = Integer.parseInt(rawdata[5]);
      int duration = Integer.parseInt(rawdata[6]);
      int capacity = Integer.parseInt(rawdata[7]);
      
      return new Request(name,eventname,new GregorianCalendar(year,month,day),startingtime,duration,capacity);
   }
   
   /**Return integer representation of a month
    * 
    * @param amonth month in string
    * @return month in integer
    * @throws IllegalArgumentException thrown when input is incorrect
    */
   public static int getMonthInt(String amonth) throws IllegalArgumentException
   {
      int position = -1;
      String months[] = {"January", "February", "March", "April", "May", "June", "July", "August",
            "September", "October", "November", "December" }; 
      for(int i=0;i<months.length;i++)
      {
         if(amonth.compareToIgnoreCase(months[i])==0)
         {
            position = i;
         }
      }
      if(position == -1)
         throw new IllegalArgumentException("Invalid Month Input.");
      return position;
   }

}
